//
//  HDHLJUAPIService.swift
//  Excited
//
//  Created by X140Yu on 7/23/16.
//  Copyright © 2016 X140Yu. All rights reserved.
//

import Foundation
import Moya
import RxSwift

let HDSchoolAPIProvider = RxMoyaProvider<HDSchoolAPIService>(endpointClosure: endpointClosure, requestClosure: requestClosure)

public enum HDSchoolAPIService {
    /// 获取 Cookie B
    case GetCookie
    /// 获取验证码图片
    case GetCaptcha
    /// 登录到教务处
    case Login(username: String, password: String, captcha: String)
    /// 获取真实姓名
    case GetRealName
}

extension HDSchoolAPIService : TargetType {
    public var baseURL: NSURL { return NSURL(string: "http://my.hlju.edu.cn")! }
    public var path: String {
        switch self {
        case .GetCookie:
            return "/login.portal"
        case .GetCaptcha:
            return "/captchaGenerate.portal"
        case .Login(_, _, _):
            return "/userPasswordValidate.portal"
        case .GetRealName:
            return "/index.portal"
        }
    }
    public var method: Moya.Method {
        switch self {
        default:
            return .GET
        }
    }
    public var parameters: [String: AnyObject]? {
        switch self {
        case .Login(let username, let password, let captcha):
            return ["Login.Token1": username, "Login.Token2": password, "captcha": captcha]
        default:
            return nil;
        }
    }
    public var sampleData: NSData {
        return "fuck".dataUsingEncoding(NSUTF8StringEncoding)!
    }
    public var multipartBody: [MultipartFormData]? {
        return nil
    }
}

private let endpointClosure: MoyaProvider<HDSchoolAPIService>.EndpointClosure = { (target) -> Endpoint<HDSchoolAPIService> in
    let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
    let endpoint: Endpoint<HDSchoolAPIService> = Endpoint<HDSchoolAPIService>(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)

    debugPrint("-- Request --")
    debugPrint(url)
    debugPrint(target.method)
    if let param = target.parameters {
        debugPrint(param)
    }
    debugPrint("-- End --")

    switch target {
    case .GetCaptcha, .Login:
        if let cookie = HDCookieManager.sharedInstance.getCookie(.B) {
            return endpoint.endpointByAddingHTTPHeaderFields(["Cookie": cookie])
        }
    case .GetRealName:
        if let cookie = HDCookieManager.sharedInstance.getCookie(.D) {
            return endpoint.endpointByAddingHTTPHeaderFields(["Cookie": cookie])
        }
    default:
        break
    }
    return endpoint
}

private let requestClosure: MoyaProvider<HDSchoolAPIService>.RequestClosure = { (endpoint, done) in
    let request: NSMutableURLRequest = endpoint.urlRequest.mutableCopy() as! NSMutableURLRequest
    request.HTTPShouldHandleCookies = false
    request.timeoutInterval = 10
    let cookieJar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
    for cook in cookieJar.cookies! {
        cookieJar.deleteCookie(cook)
    }
    done(.Success(request))
}